package com.lsyw.intergrate.common.excepion;

import cn.dev33.satoken.exception.DisableLoginException;
import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.exception.NotPermissionException;
import cn.dev33.satoken.exception.NotRoleException;
import com.lsyw.intergrate.common.Result;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import static com.lsyw.intergrate.common.Result.ERROR;

/**
 * @author liulei
 * @version 1.0
 * @date 2022/3/12 9:37
 * 全局异常处理
 */
//@ControllerAdvice
public class GlobalException {
    /**
     * 全局异常拦截（拦截项目中的所有异常）
      */
    @ResponseBody
    @ExceptionHandler
    public Result handlerException(Exception e, HttpServletRequest request, HttpServletResponse response) throws Exception {
        // 打印堆栈，以供调试
        System.out.println("全局异常---------------");
        e.printStackTrace();
        // 不同异常返回不同状态码
        Result result = null;
        //如果是未登录异常
        if (e instanceof NotLoginException) {
            NotLoginException ee = (NotLoginException) e;
            result =  new Result(ERROR,null,ee.getMessage());
        }
        else if(e instanceof NotRoleException) {
            // 如果是角色异常
            NotRoleException ee = (NotRoleException) e;
            result =  new Result(ERROR,null,ee.getMessage());
        }
        else if(e instanceof NotPermissionException) {
            // 如果是权限异常
            NotPermissionException ee = (NotPermissionException) e;
            result =  new Result(ERROR,null,"无此权限"+ee.getMessage());
        }
        else if(e instanceof DisableLoginException) {
            // 如果是被封禁异常
            DisableLoginException ee = (DisableLoginException) e;
            result =  new Result(ERROR,null,"账号被封禁："+ee.getMessage()+ "秒后解封");
        }
        else {
            // 普通异常, 输出：500 + 异常信息
            result =  new Result(ERROR,null,"500");
        }
        // 返回给前端
        return result;
    }
}
